
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.beans.PropertyVetoException;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.undo.UndoManager;

import java.net.*;
import java.io.*;

public class Logo extends JApplet implements Printable {
	
	private JDesktopPane desktop;
	private JInternalFrame JIFedit,JIFexec,JIFconsol;
	private MenuLogo menubar;
	private ToolBarLogo toolbar;
	
	private Editeur edit;
	private Execution exec;
	private Console consol;
	private Bibliotheque biblio;		
	
	private boolean telecommandeOn = false;	
	private Telecommande telecommande;
		
	public void init() {	
		try {
			   //UIManager.setLookAndFeel("com.birosoft.liquid.LiquidLookAndFeel");
			   //UIManager.setLookAndFeel("org.fife.plaf.Office2003.Office2003LookAndFeel");
			   UIManager.setLookAndFeel("com.nilo.plaf.nimrod.NimRODLookAndFeel");

			} catch (InstantiationException e) {System.out.println(e);
			} catch (ClassNotFoundException e) {System.out.println(e);
			} catch (UnsupportedLookAndFeelException e) {System.out.println(e);
			} catch (IllegalAccessException e) {System.out.println(e);}
			
		this.AddImage();		
		this.AddToolbar();		
		JIFedit = new JInternalFrame("Editeur",true,false,true,true);
		JIFexec = new JInternalFrame("Execution",true,false,true,true);
		JIFconsol = new JInternalFrame("Console",true,false,true,true);							
		exec = new Execution();
		consol = new Console(this);
		biblio = new Bibliotheque(this);
		edit = new Editeur(this);
		this.AddMenu();	
		this.AddDesktop();	
	}
	
	public Bibliotheque getBiblio(){return biblio;}
	public Console getConsol(){return consol;}
	public Editeur getEdit(){return edit;}
	public Execution getExec(){return exec;}
	public JInternalFrame getJIFConsol(){return JIFconsol;}
	public JInternalFrame getJIFEdit(){return JIFedit;}
	public JInternalFrame getJIFExec(){return JIFexec;}
	public MenuLogo getMenuLogo() {return menubar;}
	public ToolBarLogo getToolBarLogo() {return toolbar;}
	
	private void AddMenu(){
		menubar = new MenuLogo(this);				
   		this.setJMenuBar(menubar);
	}
	
	private void AddToolbar(){
		toolbar = new ToolBarLogo(this);
		this.add(toolbar,BorderLayout.NORTH);
	}
	
	private void AddDesktop(){				
		desktop = new JDesktopPane();								
		
		this.getContentPane().add(desktop, BorderLayout.CENTER);
		desktop.setBackground(Color.LIGHT_GRAY);
		desktop.add(JIFedit, JLayeredPane.DEFAULT_LAYER);
		desktop.add(JIFexec, JLayeredPane.DEFAULT_LAYER);
		desktop.add(JIFconsol, JLayeredPane.DEFAULT_LAYER);		
		
		int HautScreen = (int) this.getSize().getHeight();
		int LargScreen = (int) this.getSize().getWidth();
		
		//on affiche la fenetre de l'editeur
		JIFedit.getContentPane().add(edit);
		JIFedit.setSize(LargScreen/3, HautScreen-80);
		JIFedit.setLocation(1, 1);
		JIFedit.setVisible(true);
		JIFedit.setFrameIcon(new ImageIcon(Logo.Iedit));
		
		//on affiche la fenetre d'execution
		JIFexec.getContentPane().add(new JScrollPane(exec),"Center");
		JIFexec.setBounds(JIFedit.getWidth()+10,1,LargScreen-JIFedit.getWidth()-10,HautScreen*3/4-55) ;
		JIFexec.setVisible(true);
		JIFexec.setFrameIcon(new ImageIcon(Logo.Iexec));
		
		//on affiche la console
		JIFconsol.getContentPane().add(consol,"Center");									
		JIFconsol.setBounds(JIFedit.getWidth()+10,JIFexec.getHeight(),LargScreen-JIFedit.getWidth()-10,HautScreen-JIFexec.getHeight()-80);
		JIFconsol.setVisible(true);
		JIFconsol.setFrameIcon(new ImageIcon(Logo.Iconsol));
		
	}
	
	public static Image Itelecommande,Iprint,Iundo,Iredo,IsaveIMG,Ianimaltortue,IzoomM,IzoomP,Ihp,Istop,Igomme;
	public static Image Iquad,IhpOff,IflecheH,IflecheG,IflecheD,IflecheB,Itortue,Inew,Iopen,Isave,Icopy;
	public static Image Icut,Ipaste,ISearch,Iedit,Iexec,Iconsol,Iabout,Iversion;
	public static Image[] imagePalette;
	private void AddImage(){
		Itelecommande = getImage(getDocumentBase(), "imageToolbar/telecommande.png");
		Iprint = getImage(getDocumentBase(), "imageToolbar/imprimante.png");
		Iundo = getImage(getDocumentBase(), "imageToolbar/undo.png");
		Iredo = getImage(getDocumentBase(), "imageToolbar/redo.png");
		IsaveIMG = getImage(getDocumentBase(), "imageToolbar/enregistrer.png");
		Ianimaltortue = getImage(getDocumentBase(), "imageToolbar/animalTortue.png");
		IzoomM = getImage(getDocumentBase(), "imageToolbar/zoomM.png");
		IzoomP = getImage(getDocumentBase(), "imageToolbar/zoomP.png");
		Ihp = getImage(getDocumentBase(),"imageToolbar/hautparleur.png");
		IhpOff = getImage(getDocumentBase(), "imageToolbar/hautparleurOff.png");
		Istop = getImage(getDocumentBase(), "imageToolbar/stop.gif");
		Igomme = getImage(getDocumentBase(), "imageToolbar/gomme.png");
		Iquad = getImage(getDocumentBase(), "imageToolbar/quadrillage.png");		
		IflecheH = getImage(getDocumentBase(), "imageToolbar/FlecheH.png");
		IflecheG = getImage(getDocumentBase(), "imageToolbar/FlecheG.png");
		IflecheD = getImage(getDocumentBase(), "imageToolbar/FlecheD.png");
		IflecheB = getImage(getDocumentBase(), "imageToolbar/FlecheB.png");		
		Itortue = getImage(getDocumentBase(), "imageToolbar/tortue.png");		
		Inew = getImage(getDocumentBase(), "imageToolbar/nouveau.png");
		Iopen = getImage(getDocumentBase(), "imageToolbar/open.png");
		Isave = getImage(getDocumentBase(), "imageToolbar/save.png");
		Icopy = getImage(getDocumentBase(), "imageToolbar/copy.png");
		Icut = getImage(getDocumentBase(), "imageToolbar/cut.png");
		Ipaste = getImage(getDocumentBase(), "imageToolbar/paste.png");
		ISearch = getImage(getDocumentBase(), "imageToolbar/search.png");		
		Iedit = getImage(getDocumentBase(), "imageToolbar/editeur.png");
		Iexec = getImage(getDocumentBase(), "imageToolbar/execution.png");
		Iconsol = getImage(getDocumentBase(), "imageToolbar/console.png");
		Iabout = getImage(getDocumentBase(), "imageToolbar/about.png");
		Iversion = getImage(getDocumentBase(), "imageToolbar/help.png");
		imagePalette = new Image[6];
		imagePalette[0]= getImage(getDocumentBase(), "imageToolbar/carreBlanc.gif");
		imagePalette[1]= getImage(getDocumentBase(), "imageToolbar/carreBleu.gif");
		imagePalette[2]= getImage(getDocumentBase(),"imageToolbar/carreJaune.gif");
		imagePalette[3]= getImage(getDocumentBase(), "imageToolbar/carreNoir.gif");
		imagePalette[4]= getImage(getDocumentBase(), "imageToolbar/carreRouge.gif");
		imagePalette[5]= getImage(getDocumentBase(), "imageToolbar/carreVert.gif");	
				
	}
	

	/*****outils sur l'editeur*****/
	private File currentPath = (new JFileChooser()).getCurrentDirectory(); 
	private String currentFile;
	private FiltreFichier FFLogo = new FiltreFichier( new String[]{"logo"},"Document Logo : *.logo");
	private FiltreFichier FFText = new FiltreFichier( new String[]{"txt"},"Document texte : *.txt"); 
	
	//ouvrir dans un nouvel editeur
	public void ouvrir()
	{
		JFileChooser choix = new JFileChooser();
		choix.setCurrentDirectory(currentPath);		
		choix.addChoosableFileFilter(FFText);
		choix.addChoosableFileFilter(FFLogo);
		int retour = choix.showOpenDialog(getParent());
		if(retour == JFileChooser.APPROVE_OPTION) {			
			currentFile = choix.getSelectedFile().getAbsolutePath(); 
			currentPath = choix.getSelectedFile().getAbsoluteFile();			
			edit.lecture(currentFile); //ouverture du fichier
			consol.sys("Ouverture du fichier : "+currentFile);
		}
	}
	
	//enregistrer sous l'editeur courant
	public void enregistrerSous()
	{
		JFileChooser choix = new JFileChooser();
		choix.setCurrentDirectory(currentPath);
		choix.addChoosableFileFilter(FFText);
		choix.addChoosableFileFilter(FFLogo);
		int retour = choix.showSaveDialog(getParent());
		if(retour == JFileChooser.APPROVE_OPTION) {			
			String extensionSelectionner = choix.getFileFilter().getDescription().substring(choix.getFileFilter().getDescription().indexOf("*")+1,choix.getFileFilter().getDescription().length());
			currentFile = choix.getSelectedFile().getAbsolutePath(); //sauvegarde du nom fichier			
			if(choix.getSelectedFile().toString().lastIndexOf(".")>0)
			{					
				if(!choix.getSelectedFile().toString().substring(
							choix.getSelectedFile().toString().lastIndexOf("."),
							choix.getSelectedFile().toString().length()).equals(extensionSelectionner))
					{currentFile+=extensionSelectionner;}
			}
			else {currentFile+=extensionSelectionner;}
			currentPath = choix.getSelectedFile().getAbsoluteFile();
			choix.setCurrentDirectory(currentPath.getParentFile());
			edit.ecrire(currentFile);
			edit.setSave(true);
			edit.setModif(false);
			consol.sys("Fichier enregistre : "+currentFile);
		}
	}
	
	//enregistrer l'editeur courant
	public void enregistrer()	
	{
		boolean aSauvegarder = edit.isSave();
		if (aSauvegarder) 
		{			
			edit.ecrire(currentFile);
			if (edit.isModif())
			{
				if(edit.getTitle().lastIndexOf("*")>0)
					JIFedit.setTitle(JIFedit.getTitle().substring(0,JIFedit.getTitle().length()-1));
				consol.sys("Fichier enregistre : "+currentFile);
			}
			edit.setSave(true);
			edit.setModif(false);
		}
		else {this.enregistrerSous();}		
	}
	
	//Nouvel editeur
	public void nouveau()
	{
		edit.nouveau();
		consol.sys("Creation d'une nouvel editeur");
	}
	/*****fin outils sur l'editeur*****/

	/*****impression*****/
	private Boolean code;	
	public void impression(String imp)
	{

		code = imp.compareTo("code")==0;
			
		PrinterJob printJob = PrinterJob.getPrinterJob();
		printJob.setPrintable(this);		
		if (printJob.printDialog()) 
		{
			try { printJob.print(); }
			catch(Exception PrinterExeception) { }
		}
	}
	
	public int print(Graphics g, PageFormat pf, int pi) throws PrinterException 
	{
		if (pi >= 1) {return Printable.NO_SUCH_PAGE;}
		g.translate(100, 100);
		Font f = new Font("Monospaced",Font.PLAIN,12);
		g.setFont (f);
		if(code)
			edit.getJTexteArea().paint(g);
		else
			exec.paint(g);
		return Printable.PAGE_EXISTS;		 
	}
	/*****fin impression*****/
	
	
	//Gestion de la telecommande
	public boolean isTelecommandeOn(){return telecommandeOn;} //utile?
	public void setTelecommandeOn(boolean teleOn){telecommandeOn=teleOn;} //utile?
	public void setTelecommande()
	{
		if(!telecommandeOn)
			{telecommande = new Telecommande(this);	telecommandeOn=true;
			 consol.sys("telecommande ON");}
		else {telecommande.fermerTelecommande();telecommandeOn= false;
			  consol.sys("telecommande OFF");}
	}
	
	//Gestion des boutons Undo/Redo
	public void updateButtonsUndoRedo() {
	    toolbar.BUndo.setEnabled(edit.getJTexteLogo().undoManager.canUndo());
	    toolbar.BRedo.setEnabled(edit.getJTexteLogo().undoManager.canRedo());
	    menubar.itemUndo.setEnabled(edit.getJTexteLogo().undoManager.canUndo());
	    menubar.itemRedo.setEnabled(edit.getJTexteLogo().undoManager.canRedo());
	  }
	
	public String lireMessage(String typeMessage) 
	{
		String retour = JOptionPane.showInputDialog(typeMessage);
		return retour;
	}
}

